﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MvcCms.Service.Code.Membership
{
    public static class PasswordGenerator
    {
        public static string GeneratePassword(int length)
        {
            string allowedLowerLetterChars = "abcdefghijkmnpqrstuvwxyz";
            string allowedUpperLetterChars = "ABCDEFGHJKLMNPQRSTUVWXYZ";
            string allowedNumberChars = "23456789";
            string allowedSpecialChars = "!@$^*-_";
            char[] chars = new char[length];
            Random rd = new Random();

            bool useLetter = true;
            bool useLower = true;
            for (int i = 0; i < length - 1; i++)
            {
                if (useLetter)
                {
                    if (useLower)
                    {
                        chars[i] = allowedLowerLetterChars[rd.Next(0, allowedLowerLetterChars.Length)];
                        useLower = false;
                    }
                    else
                    {
                        chars[i] = allowedUpperLetterChars[rd.Next(0, allowedUpperLetterChars.Length)];
                        useLower = true;
                    }
                    useLetter = false;
                }
                else
                {
                    chars[i] = allowedNumberChars[rd.Next(0, allowedNumberChars.Length)];
                    useLetter = true;
                }

            }
            chars[length - 1] = allowedSpecialChars[rd.Next(0, allowedSpecialChars.Length)];
            ////add in a special char
            //var charToReplace = rd.Next(0, length);
            //chars[charToReplace] = allowedSpecialChars[rd.Next(0, allowedSpecialChars.Length)];

            return new string(chars);
        }
    }
}
